<?php
//require 'function.php';

define(PRICE_LOG, 'price.log');

//coin match array
$match_arr = array('btc' => 1, 'eth' => 1, 'eos' => 1, 'ltc' => 1, 'bch' => 1, 'etc' => 1, 'xrp' => 1, 'bsv' => 1, 'ada' => 1);


if (file_exists(PRICE_LOG)) {
    //echo "exist!<br/>";
	$now = time();
	$logcontent = file_get_contents(PRICE_LOG);
        $logcontentObj = json_decode($logcontent);
	$timestr = $logcontentObj->time;
        //echo "now:".$now.",timestr:".$timestr."<br/>";
	//if the data has expired
	if ($now >= $timestr) {
		getPrices();
		$tomorrow = strtotime(date('Ymd',strtotime("+1 day")));
		$match_arr['time'] = $tomorrow;//新的过期时间
		$logcontentObj = $match_arr;
                $logf = fopen(PRICE_LOG, "w") or error('1', '读取数据失败!');
		fwrite($logf, json_encode($logcontentObj));
                fclose($logf);
	}
	
	info($logcontentObj);
}
else {
    //echo "not exist!";
	getPrices();
	$tomorrow = strtotime(date('Ymd',strtotime("+1 day")));
	$match_arr['time'] = $tomorrow;//新的过期时间
	$logf = fopen(PRICE_LOG, "w+") or error('2', '读取数据失败!');
        fwrite($logf, json_encode($match_arr));
        fclose($logf);

	info($match_arr);
}

//request price match
function getPrices()
{
    global $match_arr;
	foreach ($match_arr as $coin => $price) {
		$back_jsontext = file_get_contents("https://api.huobi.pro/market/history/kline?period=1day&size=1&symbol=".$coin."usdt");
		$back_jsonobj = json_decode($back_jsontext);
                $k_arr = $back_jsonobj->data;
                $k_obj_0 = $k_arr[0];
		$match_arr[$coin] = $k_obj_0->open;
                sleep(1);
	}
}

function error($code,$msg)
{
	$content = array('code' => $code, 'message'=>$msg);
	echo json_encode($content);
	exit();
}

function info($data)
{
	$content = array('code' => 0, 'data'=>$data);
	echo json_encode($content);
	exit();
}

?>